package com.ctrip.ec.api.mobile.controller;

import com.ctrip.ec.api.mobile.aop.AuthLogin;
import com.ctrip.ec.api.mobile.common.JsonBody;
import com.ctrip.ec.api.mobile.common.RequestContext;
import com.ctrip.ec.api.mobile.common.ValidateException;
import com.ctrip.ec.api.mobile.model.payment.CartGoodsModel;
import com.ctrip.ec.api.mobile.model.payment.CartListModel;
import com.ctrip.ec.biz.dao.goods.GoodsDao;
import com.ctrip.ec.biz.dao.goods.GoodsImageDao;
import com.ctrip.ec.biz.dao.goods.GoodsSpecDao;
import com.ctrip.ec.biz.entity.goods.GoodsEntity;
import com.ctrip.ec.biz.entity.goods.GoodsSpecEntity;
import com.ctrip.ec.dal.PagerSetting;

import com.ctrip.ec.biz.dao.cart.CartDao;
import com.ctrip.ec.biz.entity.cart.CartEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("cart")
public class CartController {
    @Autowired
    private CartDao cart;

    @Autowired
    private GoodsDao goods;

    @Autowired
    private GoodsImageDao goodsImage;

    @Autowired
    private GoodsSpecDao goodsSpec;

    @Value("${imageDomain}")
    private String imageDomain;

    @GetMapping("list")
    @AuthLogin
    public List<CartListModel> list() throws SQLException {

        PagerSetting setting = new PagerSetting();
        setting.setOrderBy("id desc");
        setting.setWhere("member_id=" + RequestContext.getMemberId());
        List<CartEntity> cartList = cart.list(setting);
        List<GoodsEntity> goodsList = goods.listByIds(cartList.stream().map(T -> T.getGoodsId()).collect(Collectors.toList()));
        List<GoodsSpecEntity> goodsSpecList = goodsSpec.listByIds(cartList.stream().map(t->t.getSpecId()).collect(Collectors.toList()));

        List<CartGoodsModel> goodsModels = new ArrayList<>();
        for (GoodsEntity entity : goodsList) {
            CartGoodsModel model = new CartGoodsModel(entity);
            model.setOriginalImg(this.imageDomain + model.getOriginalImg());
            goodsModels.add(model);
        }

        List<CartListModel> list = new ArrayList<>();
        for (CartEntity entity : cartList) {
            CartListModel model = new CartListModel(entity);
            List<CartGoodsModel> tmpList = goodsModels.stream().filter(T -> T.getId().equals(entity.getGoodsId())).collect(Collectors.toList());
            if (tmpList != null && tmpList.size() > 0) {
                CartGoodsModel cartGoodsModel = tmpList.get(0);
                Optional< GoodsSpecEntity> goodsSpecEntity = goodsSpecList.stream().filter(t->t.getId().equals(entity.getSpecId())).findFirst();
                if (cartGoodsModel.getIsOnSale() && goodsSpecEntity.isPresent()) {
                    cartGoodsModel.setShopPrice(goodsSpecEntity.get().getShopPrice());
                    model.setGoodsSpec(goodsSpecEntity.get());
                    model.setGoods(cartGoodsModel);
                }else{
                    this.cart.delete(model.getId());
                }

            }
            list.add(model);
        }
        //  RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return list;
    }

    @GetMapping("detail/{id}")
    @AuthLogin
    public CartEntity detail(@PathVariable Long id) throws SQLException {
        CartEntity entity = cart.entity(id);
        if (!entity.getMemberId().equals(RequestContext.getMemberId())) {
            throw new ValidateException("只能查看自己的购物车");
        }
        return entity;
    }

    @PostMapping("save")
    @AuthLogin
    public Long save(@RequestBody CartEntity entity) throws SQLException {
        if (entity.add()) {
            CartEntity tmp = cart.entityBySpecId(entity.getSpecId(), RequestContext.getMemberId());
            if (tmp != null) {
                tmp.setGoodsNum(tmp.getGoodsNum() + 1);
                cart.save(tmp);
                return tmp.getId();

            } else {
                entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                entity.setMemberId(RequestContext.getMemberId());
            }
        }
        cart.save(entity);
        return entity.getId();
    }

    @PostMapping("delete")
    @AuthLogin
    public void delete(@RequestBody List<Long> ids) throws SQLException {
        List<CartEntity> list = cart.listByIds(ids);
        for (CartEntity entity : list) {
            if (!entity.getMemberId().equals(RequestContext.getMemberId())) {
                throw new ValidateException("只能删除自己的购物车");
            }
        }
        cart.delete(ids);
    }

    @GetMapping("test")
    @JsonBody(false)
    public  CartListModel test(){
         //return null;
        CartListModel model =  new CartListModel();
      //  model.setGoods(new CartGoodsModel());
        model.setGoodsSpec(new GoodsSpecEntity());
        return model;
    }

}
